package com.heima.article.listener;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ArticleConfigMapper;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.common.constants.WmNewsMessageConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class DownOrUpListener {

    @Autowired
    private ArticleConfigMapper articleConfigMapper;
    /*
    监听文章上下架功能
     */
   @RabbitListener(
           bindings = @QueueBinding(
                   value = @Queue(name = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_QUEUE,durable = "true"),
                   exchange = @Exchange(name = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,type = ExchangeTypes.TOPIC),
                   key = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_ROUTINGKEY
           )
   )
    public void getMessage(String  message){
       log.info("文章上下架监听到消息：{}", message);
       // 1、获取消息的内容
       JSONObject jsonObject = JSONObject.parseObject(message);
       Long articleId = (Long) jsonObject.get("articleId");
       Integer enable = (Integer) jsonObject.get("enable");

       // 2、根据文章id修改文章的配置

       ApArticleConfig apArticleConfig = articleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, articleId));
       if (enable == 0) {
           apArticleConfig.setIsDown(false);
       } else if (enable == 1) {
           apArticleConfig.setIsDown(true);
       }
       int i = articleConfigMapper.updateById(apArticleConfig);
       if (i <= 0) {
           log.error("文章配置更新失败！");
           throw new RuntimeException("文章配置更新失败！");
       }
    }
}
